<template>
	<view class="container">
		<!-- 导航栏 -->
		<view class="nav-bar">
			<view class="global-header-left" @click="goBack">
				<view class="global-back-button">
					<text class="global-back-icon">‹</text>
				</view>
				<text class="global-back-text">返回</text>
			</view>
		</view>
		
		<!-- 内容区域 -->
		<view class="content-wrapper">
			<!-- 背景图片 -->
			<image 
				class="background-image" 
				:src="getImageUrl('draw.png')" 
				mode="widthFix"
			></image>
		
		<!-- 标题区域 -->
			<!-- <view class="title-section">
				<image class="prize-link" :src="getImageUrl('资源 20.png')" @click="goToMyPrizes" mode="aspectFit"></image>
			</view> -->
		
			<!-- 抽奖区域box -->
			<view class="lottery-box">
		<!-- 九宫格抽奖 -->
		<view class="lottery-grid">
			<view 
				class="grid-item" 
				v-for="(item, index) in prizeItems" 
				:key="index"
				:class="{ 'selected': selectedIndex === index }"
				@click="selectItem(index)"
			>
				<view v-if="index === 4" class="center-button" :class="{ 'disabled': lotteryTimes <= 0 }" @click="startLottery">
					<image class="center-button-image" :src="getImageUrl('资源 32-8.png')" mode="aspectFit"></image>
				</view>
				<view v-else class="prize-item">
					<image 
						:src="getImageUrl('资源 26-8.png')" 
						class="prize-image"
						mode="aspectFit"
					/>
				</view>
						<!-- 选中状态的覆盖图片 -->
						<image 
							v-if="selectedIndex === index" 
							class="selected-overlay" 
							:src="getImageUrl('资源 27-8.png')" 
							mode="aspectFit"
						/>
			</view>
		</view>
		
		<!-- 抽奖次数显示 -->
		<!-- <view class="lottery-times-info">
			<text class="lottery-times-text">当前抽奖机会：{{ lotteryTimes }} 次</text>
		</view> -->
		
		<!-- 抽奖说明 -->
		<!-- <view class="lottery-instructions">
			<text class="instruction-text">
				完成"公益捐步""周边领取""门店打卡""行走的歌单"四项任务中的任意一项,即可解锁抽奖机会,欢迎参与!
			</text>
				</view> -->
			</view>
		</view>
		
		<!-- 抽奖结果弹窗 -->
		<view class="result-modal-overlay" v-if="showResultModal" @click="closeResultModal">
			<view class="result-modal-container" @click.stop>
				<image 
					class="result-modal-bg" 
					:src="getImageUrl('资源 35-8.png')" 
					mode="aspectFill"
				></image>
				<view class="result-modal-content">
					<!-- 未中奖 -->
					<template v-if="!isWinner">
						<text class="result-title lose-title">谢谢参与</text>
						<text class="result-subtitle"></text>
						<view class="result-character-wrapper">
							<image 
								class="result-character animated-character" 
								:src="getImageUrl('资源 33-8.png')" 
								mode="aspectFit"
							></image>
						</view>
						<button class="result-action-btn" @click="closeResultModal">知道了</button>
					</template>
					<!-- 中奖 -->
					<template v-else>
						<text class="result-title win-title">恭喜抽中奖品</text>
						<text class="result-prize-name">{{ prizeName }}</text>
						<!-- 小人图（中奖也显示，避免界面过空） -->
						<view class="result-character-wrapper">
							<image 
								class="result-character animated-character" 
								:src="getImageUrl('资源 33-8.png')" 
								mode="aspectFit"
							></image>
						</view>
						<button 
							class="result-action-btn win-btn" 
							@click="viewPrize"
						>查看奖品</button>
						<!-- <view class="result-agreement" @click="toggleAgreement">
							<view class="agreement-checkbox" :class="{ 'checked': agreementChecked }"></view>
							<text class="agreement-text">已阅读并同意 用户协议和隐私政策</text>
						</view> -->
					</template>
				</view>
			</view>
		</view>
	
		<!-- 奖品弹窗 -->
		<view class="prize-modal-overlay" v-if="showPrize" @click="hidePrizeModal">
			<view class="prize-modal-container" @click.stop>
				<!-- 头部固定区域 -->
				<view class="prize-modal-header">
					<!-- 标题 -->
					<text class="prize-modal-title">我的奖品</text>
					<!-- 关闭按钮 -->
					<view class="prize-modal-close" @click="hidePrizeModal">
						<text class="close-icon">×</text>
					</view>
				</view>
				
				<!-- 标签页导航 -->
				<view class="prize-tabs">
					<view 
						class="prize-tab" 
						:class="{ 'prize-tab-active': selectedPrizeWeek === 1 }"
						@click="selectedPrizeWeek = 1"
					>
						<text class="prize-tab-text">第一周奖品</text>
					</view>
					<view 
						class="prize-tab" 
						:class="{ 'prize-tab-active': selectedPrizeWeek === 2 }"
						@click="selectedPrizeWeek = 2"
					>
						<text class="prize-tab-text">第二周奖品</text>
					</view>
				</view>
				
				<!-- 滚动内容区域 -->
				<scroll-view class="prize-modal-content" scroll-y="true" enable-flex="true">
					<view class="prize-list">
						<!-- 有奖品时显示列表 -->
						<template v-if="filteredPrizes.length > 0">
						<view 
							class="prize-card" 
								v-for="(prize, index) in filteredPrizes" 
							:key="index"
						>
							<view class="prize-card-left">
								<text class="prize-name">{{ prize.name }}</text>
							</view>
							<view class="prize-card-right">
								<button 
									class="prize-action-btn" 
									:class="{ 'prize-action-btn-disabled': prize.status === 'claimed' }"
									@click="handlePrizeAction(prize)"
								>
									{{ prize.actionText }}
								</button>
							</view>
							</view>
						</template>
						<!-- 无奖品时显示空状态提示 -->
						<view class="prize-empty" v-else>
							<text class="prize-empty-text">暂无奖品</text>
							<text class="prize-empty-hint">奖品需要抽奖才有机会获取哦~</text>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		
		<!-- 证书查看弹窗 -->
		<view v-if="showCertificateModal" class="certificate-modal-overlay" @click="closeCertificateModal">
			<view class="certificate-modal-container" @click.stop>
				<!-- 关闭按钮 -->
				<view class="certificate-close" @click="closeCertificateModal">
					<image class="certificate-close-icon" src="/static/资源 1-8.png" mode="aspectFit"></image>
				</view>
				<!-- 证书图片 -->
				<scroll-view class="certificate-content" scroll-y="true">
					<image class="certificate-image" :src="certificateDisplayUrl" mode="widthFix" @error="onCertificateImageError"></image>
				</scroll-view>
				<!-- 保存按钮 -->
				<view class="certificate-footer">
					<button class="certificate-save-btn" @click="saveCertificate">保存到相册</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { login } from '@/api'
import { lottery } from '@/api/lottery'
import { getImageUrl } from '@/api/config'

export default {
	data() {
		return {
			selectedIndex: null, // 初始化时不选中任何方块
			isSpinning: false,
			prizeItems: Array(9).fill(''), // 9个格子，索引4是中心按钮
			showPrize: false,
			showResultModal: false, // 抽奖结果弹窗显示状态
			isWinner: false, // 是否中奖
			prizeName: '', // 奖品名称
			prizeImage: '', // 奖品图片
			prizeCardNumber: '', // 兑换码（卡号）
			agreementChecked: true, // 协议勾选状态
			// 奖品数据
			prizes: [],
			// 奖品弹窗选中的周次（1: 第一周, 2: 第二周）
			selectedPrizeWeek: 1,
			// 证书弹窗
			showCertificateModal: false,
			certificateUrl: 'https://hykoc.oss-cn-beijing.aliyuncs.com/koc/tc2025/certification3.jpg',
			certificateDisplayUrl: 'https://hykoc.oss-cn-beijing.aliyuncs.com/koc/tc2025/certification3.jpg',
			// 抽奖次数
			lotteryTimes: 0,
			// 抽奖次数原始数据（用于获取抽奖类型）
			lottryTimesData: []
		}
	},
	onLoad() {
		// 页面加载时获取奖品数据
		this.fetchPrizes()
	},
		computed: {
			// 根据选中的周次过滤奖品（weekNumber: '1' 或 '2'）
			filteredPrizes() {
				if (!Array.isArray(this.prizes) || this.prizes.length === 0) {
					return []
				}
				const targetWeek = this.selectedPrizeWeek === 2 ? '2' : '1'
				return this.prizes.filter((p) => {
					const wn = p?.originalData?.weekNumber
					const normalized = wn !== undefined && wn !== null ? String(wn) : '1'
					return normalized === targetWeek
				})
			}
		},
	methods: {
		getImageUrl,
		goBack() {
			uni.navigateBack()
		},
		goToMyPrizes() {
			this.showPrizeModal()
		},
		showPrizeModal() {
			this.showPrize = true
		},
		hidePrizeModal() {
			this.showPrize = false
		},
		handlePrizeAction(prize) {
			if (prize.status === 'claimed') {
				return
			}
			switch(prize.status) {
				case 'available':
					// 领取逻辑
					uni.showToast({
						title: '领取成功',
						icon: 'success'
					})
					prize.status = 'claimed'
					prize.actionText = '已领取'
					break
				case 'code':
					// 跳转到兑换奖品页面
					// 判断奖品类型：京东E卡或QQ音乐
					let prizeType = 'jd'
					if (prize.name && (prize.name.includes('QQ音乐') || prize.name.includes('qq音乐'))) {
						prizeType = 'qqmusic'
					}
					// 使用原始数据中的卡号和卡密
					const cardNumber = prize.originalData?.cardNumber || ''
					const cardSecret = prize.originalData?.cardSecret || ''
			uni.navigateTo({
						url: `/pages/prize/redeem?type=${prizeType}&code=${encodeURIComponent(cardNumber)}&secret=${encodeURIComponent(cardSecret)}&name=${encodeURIComponent(prize.name || '')}`
					})
					// 关闭奖品弹窗
					this.hidePrizeModal()
					break
				case 'certificate':
					// 弹出证书查看弹窗
					this.hidePrizeModal()
					this.certificateDisplayUrl = this.certificateUrl
					this.showCertificateModal = true
					break
				case 'store':
					// 门店领取逻辑
					uni.showToast({
						title: '请前往指定门店领取',
						icon: 'none'
			})
					break
			}
		},
		selectItem(index) {
			if (index === 4) return // 中心按钮不参与选择
			this.selectedIndex = index
		},
		async startLottery() {
			if (this.isSpinning) return
			// 检查抽奖次数
			if (this.lotteryTimes <= 0) {
				return
			}
			
			// 获取第一个有次数的抽奖类型
			const availableType = this.getAvailableLotteryType()
			if (!availableType) {
				return
			}
			
			this.isSpinning = true
			
			// 在点击时就开始请求接口
			let lotteryResult = null
			
			try {
				// 调用抽奖 API
				lotteryResult = await lottery({
					lottryType: availableType
				})
			} catch (error) {
				console.error('抽奖失败:', error)
				this.isSpinning = false
				uni.showToast({
					title: '抽奖失败，请重试',
					icon: 'none',
					duration: 2000
				})
				return
			}
			
			// 九宫格顺时针顺序（排除中心按钮4）
			// 0 1 2
			// 3 4 5  -> 0,1,2,5,8,7,6,3
			// 6 7 8
			const clockwiseOrder = [0, 1, 2, 5, 8, 7, 6, 3]
			
			// 慢-快-慢的节奏配置
			const phases = [
				{ duration: 1200, interval: 200 }, // 慢速阶段：1.2秒，每200ms切换
				{ duration: 2000, interval: 50 },  // 快速阶段：2秒，每50ms切换
				{ duration: 1200, interval: 200 }  // 慢速阶段：1.2秒，每200ms切换
			]
			
			let currentPhase = 0
			let currentIndex = 0
			
			const runPhase = () => {
				if (currentPhase >= phases.length) {
					this.isSpinning = false
					this.showResult(lotteryResult)
					return
				}
				
				const phase = phases[currentPhase]
				const phaseStartTime = Date.now()
				
				const phaseInterval = setInterval(() => {
					// 在顺时针顺序中循环
					this.selectedIndex = clockwiseOrder[currentIndex % clockwiseOrder.length]
					currentIndex++
					
					// 检查是否完成当前阶段
					if (Date.now() - phaseStartTime >= phase.duration) {
						clearInterval(phaseInterval)
						currentPhase++
						runPhase()
					}
				}, phase.interval)
			}
			
			runPhase()
		},
		showResult(lotteryResult) {
			if (!lotteryResult) {
				this.isSpinning = false
				return
			}
			
			// 更新抽奖次数
			if (lotteryResult.lottryTimes) {
				this.lotteryTimes = this.calculateLotteryTimes(lotteryResult.lottryTimes)
				this.lottryTimesData = lotteryResult.lottryTimes
			}
			
			
			
			// 设置中奖结果
			this.isWinner = lotteryResult.hit || false
			
			if (this.isWinner && lotteryResult.prize) {
				// 中奖，显示奖品信息
				this.prizeName = lotteryResult.prize.name || '未知奖品'
				this.prizeImage = lotteryResult.prize.image || ''
				this.prizeCardNumber = lotteryResult.prize.cardNumber || ''
			} else {
				this.prizeName = ''
				this.prizeImage = ''
				this.prizeCardNumber = ''
			}
			
			this.showResultModal = true
		},
		/**
		 * 证书弹窗方法
		 */
		closeCertificateModal() {
			this.showCertificateModal = false
		},
		onCertificateImageError() {
			this.certificateDisplayUrl = '/static/box.png'
		},
		async saveCertificate() {
			const url = this.certificateDisplayUrl || this.certificateUrl || '/static/box.png'
			const timeoutMs = 8000
			try {
				uni.showLoading({ title: '保存中...', mask: true })
				let tempPath = ''
				// #ifndef H5
				try {
					tempPath = await this._downloadWithTimeout(url, timeoutMs)
				} catch (_) {
					try {
						tempPath = await this._getImageInfoWithTimeout(url, timeoutMs)
					} catch (_) {
						tempPath = await this._getImageInfoWithTimeout('/static/box.png', 3000)
					}
				}
				await new Promise((resolve, reject) => {
					uni.saveImageToPhotosAlbum({ filePath: tempPath, success: resolve, fail: reject })
				})
				// #endif
				// #ifdef H5
				const link = document.createElement('a')
				link.href = url
				link.download = 'certificate.png'
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
				// #endif
				uni.showToast({ title: '已保存', icon: 'success' })
			} catch (err) {
				if (err && (err.errMsg || '').includes('auth deny')) {
					uni.showModal({
						title: '提示',
						content: '需要相册权限以保存图片，是否前往设置开启？',
						success: (res) => { if (res.confirm) uni.openSetting({}) }
					})
				} else {
					uni.showToast({ title: '保存失败，请重试', icon: 'none' })
				}
			} finally {
				uni.hideLoading()
			}
		},
		_downloadWithTimeout(url, timeoutMs = 8000) {
			return new Promise((resolve, reject) => {
				let done = false
				const timer = setTimeout(() => {
					if (done) return
					done = true
					reject(new Error('download timeout'))
				}, timeoutMs)
				uni.downloadFile({
					url,
					success: (res) => {
						if (done) return
						done = true
						clearTimeout(timer)
						if (res.statusCode === 200) resolve(res.tempFilePath)
						else reject(new Error('下载失败'))
					},
					fail: (err) => {
						if (done) return
						done = true
						clearTimeout(timer)
						reject(err)
					}
				})
			})
		},
		_getImageInfoWithTimeout(src, timeoutMs = 8000) {
			return new Promise((resolve, reject) => {
				let done = false
				const timer = setTimeout(() => {
					if (done) return
					done = true
					reject(new Error('getImageInfo timeout'))
				}, timeoutMs)
				uni.getImageInfo({
					src,
					success: (info) => {
						if (done) return
						done = true
						clearTimeout(timer)
						resolve(info.path || info.tempFilePath)
					},
					fail: (err) => {
						if (done) return
						done = true
						clearTimeout(timer)
						reject(err)
					}
				})
			})
		},
		/**
		 * 获取第一个有次数的抽奖类型
		 * @returns {String|null} 抽奖类型，如果没有则返回 null
		 */
		getAvailableLotteryType() {
			if (!Array.isArray(this.lottryTimesData) || this.lottryTimesData.length === 0) {
				return null
			}
			// 找到第一个次数大于0的类型
			const available = this.lottryTimesData.find(item => {
				const times = parseInt(item.times, 10) || 0
				return times > 0
			})
			return available ? available.lottryType : null
		},
		closeResultModal() {
			this.showResultModal = false
			this.isWinner = false
			this.prizeName = ''
			this.agreementChecked = false // 重置协议勾选状态
			this.selectedIndex = null // 重置选中状态
		},
		toggleAgreement() {
			this.agreementChecked = !this.agreementChecked
		},
		viewPrize() {
			// 优先使用抽奖结果中的卡号作为兑换码
			const code = this.prizeCardNumber || ''
			if (!code) {
				uni.showToast({
					title: '兑换码生成中，请稍后重试',
					icon: 'none',
					duration: 2000
				})
				return
			}
			// 简单根据奖品名称推断类型（默认京东E卡）
			let prizeType = 'jd'
			if (this.prizeName && (this.prizeName.includes('QQ音乐') || this.prizeName.includes('qq音乐'))) {
				prizeType = 'qqmusic'
			}
			uni.navigateTo({
				url: `/pages/prize/redeem?type=${prizeType}&code=${encodeURIComponent(code)}&name=${encodeURIComponent(this.prizeName)}`
			})
			this.closeResultModal()
		},
		claimPrize() {
			// 检查是否勾选协议
			if (!this.agreementChecked) {
				uni.showToast({
					title: '请先阅读并同意用户协议',
					icon: 'none',
					duration: 2000
				})
				return
			}
			// 领取奖品逻辑
			uni.showToast({
				title: '领取成功',
				icon: 'success'
			})
			this.closeResultModal()
			// 可以在这里添加中奖记录到奖品列表
			// 重新获取奖品列表
			this.fetchPrizes()
		},
		/**
		 * 获取奖品数据
		 */
		async fetchPrizes() {
			try {
				const loginRes = await login()
				if (loginRes && loginRes.initData) {
					// 获取奖品数据
					if (loginRes.initData.prizes && Array.isArray(loginRes.initData.prizes)) {
						this.prizes = this.formatPrizes(loginRes.initData.prizes)
					} else {
						this.prizes = []
					}
					// 计算抽奖次数并保存原始数据
					if (loginRes.initData.lottryTimes) {
						this.lottryTimesData = loginRes.initData.lottryTimes
						this.lotteryTimes = this.calculateLotteryTimes(loginRes.initData.lottryTimes)
					} else {
						this.lottryTimesData = []
						this.lotteryTimes = 0
					}
				} else {
					this.prizes = []
					this.lotteryTimes = 0
					this.lottryTimesData = []
				}
			} catch (error) {
				console.error('获取奖品数据失败:', error)
				this.prizes = []
				this.lotteryTimes = 0
				this.lottryTimesData = []
			}
		},
		/**
		 * 计算总抽奖次数
		 * @param {Array} lottryTimes 抽奖次数数组
		 * @returns {Number} 总抽奖次数
		 */
		calculateLotteryTimes(lottryTimes) {
			if (!Array.isArray(lottryTimes) || lottryTimes.length === 0) {
				return 0
			}
			// 对所有对象的 times 字段求和
			return lottryTimes.reduce((total, item) => {
				const times = parseInt(item.times, 10) || 0
				return total + times
			}, 0)
		},
		/**
		 * 格式化奖品数据，将接口返回的数据转换为页面展示格式
		 * @param {Array} apiPrizes 接口返回的奖品数组
		 * @returns {Array} 格式化后的奖品数组
		 */
		formatPrizes(apiPrizes) {
			if (!Array.isArray(apiPrizes)) {
				return []
			}
			
			return apiPrizes.map(prize => {
				// 判断奖品类型
				const isVirtual = prize.prizeType === 'VIRTUAL' || prize.prizeType === 'VIRTUAL_OR_PHYSICAL_UNSPECIFIED'
				const isCertificate = prize.name && (prize.name.includes('证书') || prize.name.toLowerCase().includes('certificate'))
				const type = isVirtual ? 'virtual' : 'physical'
				const typeText = isVirtual ? '虚拟奖品' : '实物奖品'
				
				// 判断状态和操作文本
				let status = 'available'
				let actionText = '领取'
				
				// 如果有卡号和卡密，说明已发放，状态为 code（虚拟奖品）
				if (!isCertificate && prize.cardNumber) {
					status = 'code'
					actionText = '查询兑换码'
				} else if (isCertificate) {
					status = 'certificate'
					actionText = '点击查看'
				} else if (prize.recipientName || prize.recipientPhone || prize.recipientAddress) {
					// 如果有收件人信息，说明已领取（实物奖品）
					status = 'claimed'
					actionText = '已领取'
				} else if (!isVirtual) {
					// 实物奖品且没有收件人信息，需要门店领取
					status = 'store'
					actionText = '门店领取'
				}
				// 虚拟奖品且没有卡号卡密，保持 available 状态
				
				// 格式化日期（drawDate 作为过期日期显示）
				let expireDate = ''
				if (prize.drawDate) {
					// 如果 drawDate 是完整日期，直接使用；否则可能需要格式化
					const date = new Date(prize.drawDate)
					if (!isNaN(date.getTime())) {
						// 计算过期日期（假设中奖后30天过期）
						date.setDate(date.getDate() + 30)
						const year = date.getFullYear()
						const month = String(date.getMonth() + 1).padStart(2, '0')
						const day = String(date.getDate()).padStart(2, '0')
						expireDate = `${year}-${month}-${day}`
					} else {
						expireDate = prize.drawDate
					}
				}
				
				return {
					id: prize.id || '',
					name: prize.name || '未知奖品',
					type: type,
					typeText: typeText,
					expireDate: expireDate,
					status: status,
					actionText: actionText,
					// 保留原始数据，用于后续操作
					originalData: prize
				}
			})
		}
	}
}
</script>

<style scoped>
.certificate-modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.7);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 12000;
}

.certificate-modal-container {
	width: 92%;
	max-width: 680rpx;
	max-height: 90vh;
	background-color: #ffffff;
	border-radius: 24rpx;
	overflow: hidden;
	display: flex;
	flex-direction: column;
	position: relative;
}

.certificate-close {
	position: absolute;
	top: 16rpx;
	right: 16rpx;
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 2;
}

.certificate-close-icon {
	width: 60rpx;
	height: 60rpx;
}

.certificate-content {
	flex: 1;
	padding: 0;
}

.certificate-image {
	width: 100%;
	border-radius: 0;
	display: block;
}

.certificate-footer {
	padding: 20rpx;
	border-top: 1rpx solid #f0f0f0;
}

.certificate-save-btn {
	width: 100%;
	height: 88rpx;
	background: #ff4444;
	color: #ffffff;
	border: none;
	border-radius: 44rpx;
	font-size: 32rpx;
	font-weight: bold;
}

.certificate-save-btn::after {
	border: none;
}
.container {
	background: linear-gradient(to bottom, #15638C 0%, #ffffff 50%, #87ceeb 100%);
	min-height: 100vh;
	padding: 0;
	position: relative;
}

/* 导航栏 */
.nav-bar {
	z-index: 1000;
	background: transparent;
	padding-top: var(--status-bar-height, 44rpx);
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: var(--status-bar-height, 44rpx) 30rpx 20rpx;
}

/* 确保全局返回按钮样式正确应用 */
.global-back-button {
	width: 60rpx !important;
	height: 60rpx !important;
	background: #FF0000 !important;
	border-radius: 50% !important;
	display: flex !important;
	align-items: center !important;
	justify-content: center !important;
	margin-right: 15rpx !important;
}

.global-back-icon {
	color: white !important;
	font-size: 40rpx !important;
	font-weight: bold !important;
}

.global-back-text {
	color: white !important;
	font-size: 28rpx !important;
	font-weight: bold !important;
}

.global-header-left {
	display: flex !important;
	align-items: center !important;
}


/* 内容区域 */
.content-wrapper {
margin-top: 100rpx;
	padding-bottom: 40rpx;
	position: relative;
	/* min-height: 100vh; */
}

/* 背景图片 */
.background-image {
	width: 100%;
	display: block;
}

/* 标题区域 */
.title-section {
	position: absolute;
	top: 40rpx;
	right: 80rpx;
	z-index: 10;
}

.main-title {
	color: #ffffff;
	font-size: 36rpx;
	font-weight: bold;
}

.prize-link {
	width: 120rpx;
	height: 36rpx;
	cursor: pointer;
}

/* 抽奖区域box */
.lottery-box {
	border-radius: 0 0 20rpx 20rpx;
	margin: 0 30rpx;
	padding: 40rpx 30rpx;
	position: absolute;
	top: 120rpx;
	left: 0;
	right: 0;
	z-index: 10;
}

/* 3x3抽奖网格 */
.lottery-grid {
	display: grid;
	grid-template-columns: repeat(3, 1fr);
	gap: 20rpx;
	padding: 0 0 40rpx;
	max-width: 600rpx;
	margin: 0 auto;
}

.grid-item {
	aspect-ratio: 1;
	background: rgba(21, 99, 140, 0.05);
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	transition: all 0.3s ease;
}

.grid-item.selected {
	position: relative;
	/* 移除边框，改用图片覆盖 */
	/* border: 4rpx solid #ff0000 !important; */
	box-sizing: border-box;
}

.selected-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 10;
	pointer-events: none;
}


.center-button {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: opacity 0.3s ease;
}

.center-button.disabled {
	opacity: 0.5;
	cursor: not-allowed;
}

.center-button-image {
	width: 100%;
	height: 100%;
	position: relative;
	z-index: 1;
}

.prize-item {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.prize-image {
	width: 100%;
	height: 100%;
	position: relative;
	z-index: 1;
}

/* 抽奖次数显示 */
.lottery-times-info {
	padding: 10rpx 0;
	text-align: center;
}

.lottery-times-text {
	color: #FF4444;
	font-size: 28rpx;
	font-weight: bold;
	line-height: 1.5;
}

/* 抽奖说明 */
.lottery-instructions {
	padding: 0;
}

.instruction-text {
	color: #4d4d4d;
	font-size: 24rpx;
	line-height: 1.6;
	text-align: center;
}

/* 响应式调整 */
@media screen and (max-width: 750rpx) {
	.lottery-grid {
		gap: 15rpx;
		padding: 0 20rpx 30rpx;
	}
	
	.grid-item {
		border-radius: 15rpx;
	}
	
	.center-button {
		border-radius: 15rpx;
	}
	
	.button-text {
		font-size: 24rpx;
	}
	
	.character {
		font-size: 50rpx;
	}
}

/* 奖品弹窗样式 */
.prize-modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(76, 76, 76, 0.7);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 9999;
}

.prize-modal-container {
	width: 92%;
	max-width: 680rpx;
	height: 60vh;
	background-color: #FFF9F5;
	border-radius: 40rpx 40rpx 20rpx 20rpx;
	overflow: hidden;
	box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
	display: flex;
	flex-direction: column;
}

/* 头部固定区域 */
.prize-modal-header {
	background-color: #FFF9F5;
	border-radius: 40rpx 40rpx 0 0;
	padding: 40rpx 30rpx 30rpx;
	position: relative;
	flex-shrink: 0;
}

.prize-modal-title {
	display: block;
	font-size: 36rpx;
	font-weight: bold;
	color: #FF4444;
	text-align: center;
}

.prize-modal-close {
	position: absolute;
	top: 20rpx;
	right: 10rpx;
	width: 60rpx;
	height: 60rpx;
	background-color: #FF4444;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 2rpx 8rpx rgba(255, 68, 68, 0.3);
	z-index: 10;
}

.close-icon {
	color: #FFFFFF;
	font-size: 40rpx;
	font-weight: bold;
	line-height: 1;
}

/* 滚动内容区域 */
.prize-modal-content {
	flex: 1;
	overflow-y: auto;
	padding: 30rpx;
	box-sizing: border-box;
	width: 100%;
}

.prize-tabs {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 0;
	padding: 0 30rpx;
	margin-bottom: 20rpx;
	background-color: #FFF9F5;
	border-bottom: 1rpx solid #f0f0f0;
}

.prize-tab {
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 24rpx 0;
	position: relative;
	cursor: pointer;
}

.prize-tab-text {
	font-size: 28rpx;
	color: #999999;
	transition: color 0.3s ease;
	position: relative;
	z-index: 1;
}

.prize-tab-active .prize-tab-text {
	color: #ff4444;
	font-weight: bold;
}

.prize-tab-active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 110%;
	height: 4rpx;
	background-color: #ff4444;
	border-radius: 2rpx;
	z-index: 2;
}

.prize-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	width: 100%;
	box-sizing: border-box;
}

/* 奖品卡片 */
.prize-card {
	box-sizing: border-box;
	background-color: #FFFFFF;
	border: 1rpx solid #E5E5E5;
	border-radius: 16rpx;
	padding: 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 100%;
	max-width: 100%;
	overflow: hidden;
}

.prize-card-left {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 12rpx;
	margin-right: 20rpx;
	min-width: 0;
}

.prize-name {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
	line-height: 1.4;
	word-break: break-all;
	overflow-wrap: break-word;
}

.prize-detail {
	font-size: 24rpx;
	color: #999999;
	line-height: 1.4;
	word-break: break-all;
	overflow-wrap: break-word;
}

.prize-card-right {
	flex-shrink: 0;
}

.prize-action-btn {
	padding: 16rpx 32rpx;
	background-color: #FF4444;
	color: #FFFFFF;
	border: none;
	border-radius: 30rpx;
	font-size: 26rpx;
	font-weight: 500;
	white-space: nowrap;
	line-height: 1;
}

.prize-action-btn-disabled {
	background-color: #CCCCCC;
	color: #FFFFFF;
}

.prize-action-btn::after {
	border: none;
}

/* 空状态提示样式 */
.prize-empty {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 30rpx;
	width: 100%;
	box-sizing: border-box;
}

.prize-empty-text {
	font-size: 32rpx;
	color: #999999;
	margin-bottom: 20rpx;
	font-weight: 500;
}

.prize-empty-hint {
	font-size: 26rpx;
	color: #CCCCCC;
	text-align: center;
	line-height: 1.5;
}

/* 抽奖结果弹窗样式 */
.result-modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(76, 76, 76, 0.7);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 10000;
}

.result-modal-container {
	width: 90%;
	max-width: 680rpx;
	position: relative;
	border-radius: 40rpx;
	overflow: hidden;
	box-shadow: 0 10rpx 40rpx rgba(0, 0, 0, 0.3);
	min-height: 600rpx;
}

.result-modal-bg {
	width: 100%;
	height: 100%;
	position: absolute;
	top: 0;
	left: 0;
	z-index: 0;
	object-fit: cover;
}

.result-modal-content {
	position: relative;
	z-index: 1;
	padding: 60rpx 50rpx 50rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: flex-start;
	min-height: 600rpx;
	box-sizing: border-box;
}

/* 标题样式 */
.result-title {
	display: block;
	font-size: 48rpx;
	font-weight: bold;
	text-align: center;
	margin-bottom: 20rpx;
	line-height: 1.2;
}

.lose-title {
	color: #FF4444;
}

.win-title {
	color: #FF4444;
}

.result-subtitle {
	display: block;
	font-size: 32rpx;
	color: #FF6666;
	text-align: center;
	margin-bottom: 40rpx;
}

.result-prize-name {
	display: block;
	font-size: 36rpx;
	color: #333333;
	text-align: center;
	margin-bottom: 40rpx;
	font-weight: 500;
}

/* 小人图容器 */
.result-character-wrapper {
	width: 300rpx;
	height: 300rpx;
	margin: 20rpx 0 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.result-character {
	width: 100%;
	height: 100%;
}

/* 小人图动效 */
.animated-character {
	/* animation: characterBounce 1.5s ease-in-out infinite; */
}

@keyframes characterBounce {
	0%, 100% {
		transform: translateY(0) scale(1) rotate(0deg);
	}
	15% {
		transform: translateY(-15rpx) scale(1.05) rotate(-2deg);
	}
	30% {
		transform: translateY(-25rpx) scale(1.08) rotate(2deg);
	}
	45% {
		transform: translateY(-20rpx) scale(1.06) rotate(-1deg);
	}
	60% {
		transform: translateY(-10rpx) scale(1.03) rotate(1deg);
	}
	75% {
		transform: translateY(-15rpx) scale(1.04) rotate(-1deg);
	}
	90% {
		transform: translateY(-5rpx) scale(1.01) rotate(0.5deg);
	}
}

/* 奖品图片容器 */
.result-prize-image-wrapper {
	width: 400rpx;
	height: 400rpx;
	margin: 20rpx 0 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.result-prize-image {
	width: 100%;
	height: 100%;
	border-radius: 20rpx;
}

.result-prize-placeholder {
	width: 100%;
	height: 100%;
	background-color: #F5F5F5;
	border: 2rpx dashed #CCCCCC;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.placeholder-text {
	font-size: 28rpx;
	color: #999999;
}

/* 按钮样式 */
.result-action-btn {
	width: 100%;
	max-width: 500rpx;
	padding: 24rpx 0;
	background-color: #FF4444;
	color: #FFFFFF;
	border: none;
	border-radius: 50rpx;
	font-size: 32rpx;
	font-weight: bold;
	margin-top: 20rpx;
	box-shadow: 0 4rpx 12rpx rgba(255, 68, 68, 0.3);
}

.win-btn {
	margin-top: 10rpx;
}

.result-action-btn.disabled {
	background-color: #CCCCCC;
	color: #FFFFFF;
	opacity: 0.6;
}

.result-action-btn[disabled] {
	background-color: #CCCCCC;
	color: #FFFFFF;
	opacity: 0.6;
}

.result-action-btn::after {
	border: none;
}

/* 协议勾选 */
.result-agreement {
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 30rpx;
	gap: 12rpx;
	cursor: pointer;
	user-select: none;
}

.agreement-checkbox {
	width: 32rpx;
	height: 32rpx;
	border-radius: 50%;
	border: 2rpx solid #FF4444;
	position: relative;
	flex-shrink: 0;
}

.agreement-checkbox.checked {
	background-color: #FF4444;
}

.agreement-checkbox.checked::after {
	content: '✓';
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	color: #FFFFFF;
	font-size: 20rpx;
	font-weight: bold;
}

.agreement-text {
	font-size: 24rpx;
	color: #666666;
	line-height: 1.4;
}
</style>